<template>
  <div class="global-container">
    <div class="headContainer">
      <el-card style="width: 24%;" shadow="never">
        <el-row>
          <el-col :span="8" style="display: flex; justify-content: center;">
            <div style="margin-top: 5px;">
              <i class="fa fa-shopping-cart fa-3x"></i>
            </div>
          </el-col>
          <el-col :span="16">
            <div>
              <span style="font-size: 20px; font-weight: 500;">
                应用商店
              </span>
            </div>
            <div>
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :span="19">
                  <span style="display: flex; justify-content: right;">
                    服务包
                  </span>
                </el-col>
                <el-col :span="5">
                  <span style="display: flex; justify-content: right; font-size: 16px; color: gray;">
                    {{ appStoreInfo.serviceNumber }}
                  </span>
                </el-col>
              </el-row>
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :span="19">
                  <span style="display: flex; justify-content: right;">
                    云原生
                  </span>
                </el-col>
                <el-col :span="5">
                  <span style="display: flex; justify-content: right; font-size: 16px; color: gray;">
                    {{ appStoreInfo.yamlNumber }}
                  </span>
                </el-col>
              </el-row>
              <!--              <div style="margin-top: 10px; display: flex; justify-content: right;">-->
              <!--                服务包-->
              <!--                <span style="margin-left: 20px;font-size: 16px; color: gray;">-->
              <!--                  {{ appStoreInfo.serviceNumber }}-->
              <!--                </span>-->
              <!--              </div>-->
              <!--              <div style="margin-top: 10px; display: flex; justify-content: right;">-->
              <!--                云原生-->
              <!--                <span style="margin-left: 20px;font-size: 16px; color: gray;">-->
              <!--                  {{ appStoreInfo.yamlNumber }}-->
              <!--                </span>-->
              <!--              </div>-->
            </div>
          </el-col>
        </el-row>
      </el-card>
      <el-card style="width: 24%;" shadow="never">
        <el-row>
          <el-col :span="8" style="display: flex; justify-content: center;">
            <div style="margin-top: 5px;">
              <!--              <i class="fa fa-shopping-cart fa-3x"></i>-->
              <!--              <el-image-->
              <!--                style="width: 100px; height: 100px"-->
              <!--                src="@/icon/svg/component.svg"-->
              <!--                fit="fill"-->
              <!--              >-->
              <!--              </el-image>-->
              <img :src="require('@/assets/svg/component.svg')" alt="Icon" style="width: 45px; height: 45px;" />
            </div>
          </el-col>
          <el-col :span="16">
            <div>
              <span style="font-size: 20px; font-weight: 500;">
                应用管理
              </span>
            </div>
            <div>
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :span="19">
                  <span style="display: flex; justify-content: right;">
                    服务实例
                  </span>
                </el-col>
                <el-col :span="5">
                  <span style="display: flex; justify-content: right; font-size: 16px; color: gray;">
                    {{ resourceInfo.deployNumber }}
                  </span>
                </el-col>
              </el-row>
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :span="19">
                  <span style="display: flex; justify-content: right;">
                    云原生实例
                  </span>
                </el-col>
                <el-col :span="5">
                  <span style="display: flex; justify-content: right; font-size: 16px; color: gray;">
                    {{ resourceInfo.cloudDeployNumber }}
                  </span>
                </el-col>
              </el-row>
              <!--              <div style="margin-top: 10px; display: flex; justify-content: right;">-->
              <!--                服务实例-->
              <!--                <span style="margin-left: 20px;font-size: 16px; color: gray;">-->
              <!--                  {{ resourceInfo.deployNumber }}-->
              <!--                </span>-->
              <!--              </div>-->
              <!--              <div style="margin-top: 10px; display: flex; justify-content: right;">-->
              <!--                云原生实例-->
              <!--                <span style="margin-left: 20px;font-size: 16px; color: gray;">-->
              <!--                  {{ resourceInfo.cloudDeployNumber }}-->
              <!--                </span>-->
              <!--              </div>-->
            </div>
          </el-col>
        </el-row>
      </el-card>
      <el-card style="width: 24%;" shadow="never">
        <el-row>
          <el-col :span="8" style="display: flex; justify-content: center;">
            <div style="margin-top: 5px;">
              <i class="fa fa-credit-card fa-3x"></i>
            </div>
          </el-col>
          <el-col :span="16">
            <div>
              <span style="font-size: 20px; font-weight: 500;">
                租户资源
              </span>
            </div>
            <div>
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :xs="10" :sm="12" :md="12" :lg="16" :xl="18">
                  <span style="display: flex; justify-content: right;">
                    CPU
                  </span>
                </el-col>
                <el-col :xs="14" :sm="12" :md="12" :lg="8" :xl="6">
                  <span style="display: flex; justify-content: left; font-size: 16px; color: gray;">
                    {{ resourceInfo.tenantCpu }}核
                  </span>
                </el-col>
              </el-row>
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :xs="10" :sm="12" :md="12" :lg="16" :xl="18">
                  <span style="display: flex; justify-content: right;">
                    内存
                  </span>
                </el-col>
                <el-col :xs="14" :sm="12" :md="12" :lg="8" :xl="6">
                  <span style="display: flex; justify-content: left; font-size: 16px; color: gray;">
                    {{ (resourceInfo.tenantMem / 1024).toFixed(0) }}GB
                  </span>
                </el-col>
              </el-row>
              <!--              <div style="margin-top: 10px; display: flex; justify-content: right;">-->
              <!--                CPU-->
              <!--                <span style="margin-left: 20px;font-size: 16px; color: gray;">-->
              <!--                  {{ resourceInfo.tenantCpu }}-->
              <!--                </span>-->
              <!--              </div>-->
              <!--              <div style="margin-top: 10px; display: flex; justify-content: right;">-->
              <!--                内存-->
              <!--                <span style="margin-left: 20px;font-size: 16px; color: gray;">-->
              <!--                  {{ (resourceInfo.tenantMem / 1024).toFixed(1) }}-->
              <!--                </span>-->
              <!--              </div>-->
            </div>
          </el-col>
        </el-row>
      </el-card>
      <el-card style="width: 24%;" shadow="never">
        <el-row>
          <el-col :span="8" style="display: flex; justify-content: center;">
            <div style="margin-top: 5px;">
              <i class="fa fa-database fa-3x"></i>
            </div>
          </el-col>
          <el-col :span="16">
            <div>
              <span style="font-size: 20px; font-weight: 500;">
                资源申请量
              </span>
            </div>
            <div>
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :xs="10" :sm="12" :md="12" :lg="16" :xl="18">
                  <span style="display: flex; justify-content: right;">
                    CPU
                  </span>
                </el-col>
                <el-col :xs="14" :sm="12" :md="12" :lg="8" :xl="6">
                  <span style="display: flex; justify-content: left; font-size: 16px; color: gray;">
                    {{ resourceInfo.tenantRequestCpu }}核
                  </span>
                </el-col>
              </el-row>
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :xs="10" :sm="12" :md="12" :lg="16" :xl="18">
                  <span style="display: flex; justify-content: right;">
                    内存
                  </span>
                </el-col>
                <el-col :xs="14" :sm="12" :md="12" :lg="8" :xl="6">
                  <span style="display: flex; justify-content: left; font-size: 16px; color: gray;">
                    {{ (resourceInfo.tenantRequestMem / 1024).toFixed(0) }}GB
                  </span>
                </el-col>
              </el-row>
              <!--              <div style="margin-top: 10px; display: flex; justify-content: right;">-->
              <!--                CPU-->
              <!--                <span style="margin-left: 20px;font-size: 16px; color: gray;">-->
              <!--                  {{ resourceInfo.tenantRequestCpu }}-->
              <!--                </span>-->
              <!--              </div>-->
              <!--              <div style="margin-top: 10px; display: flex; justify-content: right;">-->
              <!--                内存-->
              <!--                <span style="margin-left: 20px;font-size: 16px; color: gray;">-->
              <!--                  {{ (resourceInfo.tenantRequestMem / 1024).toFixed(1) }}-->
              <!--                </span>-->
              <!--              </div>-->
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <div class="resource-stats">
      <el-row type="flex" justify="space-between">
        <el-col :span="8">
          <div style="height: 20rem;">
            <div ref="cpuChart" id="cpuChart" class="pie-chart"></div>
          </div>
        </el-col>
        <el-col :span="8">
          <div style="height: 20rem;">
            <div ref="memChart" id="memChart" class="pie-chart"></div>
          </div>
        </el-col>
        <el-col :span="8">
          <div style="height: 20rem;">
            <div ref="podChart" id="podChart" class="pie-chart"></div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div style="display: flex; justify-content: space-between; width: 100%; margin-top: 20px;">
      <el-card style="width: 49%;" shadow="never">
        <span style="font-size: 19px; font-weight: 500;">
          服务资源申请TOP5
        </span>
        <el-table :data="serviceData" style="width: 100%; margin-top: 10px;" :row-style="{ height: '2.5rem' }"
          :cell-style="{ padding: '0' }" max-height="16.75rem">
          <el-table-column label="服务名称">
            <template slot-scope="scope">
              <el-tooltip effect="dark" :content="scope.row.serviceName" placement="bottom" popper-class="tooltipClass"
                :disabled="isShowTooltip">
                <div class="descSpan" @mouseover="onMouseOver($event)">
                  {{ scope.row.serviceName }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="部署名称">
            <template slot-scope="scope">
              <el-tooltip effect="dark" :content="scope.row.deployName" placement="bottom" popper-class="tooltipClass"
                :disabled="isShowTooltip">
                <div class="descSpan" @mouseover="onMouseOver($event)">
                  {{ scope.row.deployName }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="deployCpu" label="CPU(核)" width="100">
          </el-table-column>
          <el-table-column prop="deployMem" label="内存(MB)" width="100">
          </el-table-column>
          <el-table-column prop="deployTime" label="创建时间" width="180">
          </el-table-column>
        </el-table>
      </el-card>
      <el-card style="width: 49%;" shadow="never">
        <div style="height: 18rem;">
          <div ref="logChart" id="logChart" class="pie-chart"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>

import dayjs from "dayjs";

export default {
  name: "Dashboard",
  data() {
    return {
      appStoreInfo: {
        serviceNumber: 0,
        yamlNumber: 0
      },
      isShowTooltip: false,
      resourceInfo: {
        podRunning: 0,
        podFailed: 0,
        tenantUsedMem: 0,
        tenantRequestMem: 0,
        tenantRequestCpu: 0,
        tenantMem: 0,
        tenantUsedCpu: 0,
        tenantCpu: 0,
        cloudDeployNumber: 0,
        deployNumber: 0,
      },
      serviceData: [],
      loginData: [],
      appStoreData: [],
      managerData: [],
    };
  },
  methods: {
    //重要代码
    chartResize() {
      let cpuChart = this.$echarts.getInstanceByDom(document.getElementById('cpuChart'));
      if (cpuChart == null) {
        cpuChart = this.$echarts.init(this.$refs.cpuChart);
      }
      cpuChart.resize();
      let memChart = this.$echarts.getInstanceByDom(document.getElementById('memChart'));
      if (memChart == null) {
        memChart = this.$echarts.init(this.$refs.memChart);
      }
      memChart.resize();
      let podChart = this.$echarts.getInstanceByDom(document.getElementById('podChart'));
      if (podChart == null) {
        cpuChart = this.$echarts.init(this.$refs.cpuChart);
      }
      podChart.resize();
      let logChart = this.$echarts.getInstanceByDom(document.getElementById('logChart'));
      if (logChart == null) {
        cpuChart = this.$echarts.init(this.$refs.cpuChart);
      }
      logChart.resize();
    },
    initCpuType() {
      // 基于准备好的dom，初始化echarts实例
      const cpuChart = this.$echarts.init(this.$refs.cpuChart);
      // 指定图表的配置项和数据
      const option = {
        tooltip: {
          trigger: "item",
          formatter: '{a} <br/>{b}: {c}核 ({d}%)'
        },
        title: {
          text: "租户CPU资源使用量(核)",
          left: "center",
        },
        color: ["#e05a5a", "#388bca"],
        legend: {
          right: "10",
          orient: 'vertical',
          bottom: "10",
        },
        series: [
          {
            name: "CPU",
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              // show: false,
              // position: "center",
              // formatter: `${(3 / 4) * 100 + "%"}`,
              formatter: '{b}: {c}'
              // fontSize: 30,
            },
            // emphasis: {
            //   label: {
            //     show: true,
            //     fontSize: 40,
            //     fontWeight: "bold",
            //     position: "center",
            //   },
            //   itemStyle: {
            //     shadowBlur: 10,
            //     shadowOffsetX: 0,
            //     shadowColor: 'rgba(0, 0, 0, 0.5)'
            //   }
            // },
            // labelLine: {
            //   show: false,
            // },
            data: [
              { value: `${this.resourceInfo.tenantUsedCpu}`, name: "已用" },
              { value: `${this.resourceInfo.tenantCpu - this.resourceInfo.tenantUsedCpu}`, name: "未用" },
            ],
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      cpuChart.setOption(option);
    },
    initMemType() {
      // 基于准备好的dom，初始化echarts实例
      const memChart = this.$echarts.init(this.$refs.memChart);
      // 指定图表的配置项和数据
      const option = {
        tooltip: {
          trigger: "item",
          formatter: '{a} <br/>{b}: {c}GB ({d}%)'
        },
        title: {
          text: "租户内存资源使用量(GB)",
          left: "center",
        },
        color: ["#e69840", "#F1C993"],
        legend: {
          right: "10",
          orient: 'vertical',
          bottom: "10",
        },
        series: [
          {
            name: "内存",
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              // show: false,
              // position: "center",
              // formatter: `${(3 / 4) * 100 + "%"}`,
              formatter: '{b}: {c}'
              // fontSize: 30,
            },
            // emphasis: {
            //   label: {
            //     show: true,
            //     fontSize: 40,
            //     fontWeight: "bold",
            //     position: "center",
            //   },
            //   itemStyle: {
            //     shadowBlur: 10,
            //     shadowOffsetX: 0,
            //     shadowColor: 'rgba(0, 0, 0, 0.5)'
            //   }
            // },
            // labelLine: {
            //   show: false,
            // },
            data: [
              { value: `${(this.resourceInfo.tenantUsedMem / 1024).toFixed(2)}`, name: "已用" },
              {
                value: `${((this.resourceInfo.tenantMem - this.resourceInfo.tenantUsedMem) / 1024).toFixed(2)}`,
                name: "未用"
              },
            ],
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      memChart.setOption(option);
    },
    initPodType() {
      // 基于准备好的dom，初始化echarts实例
      const podChart = this.$echarts.init(this.$refs.podChart);
      // 指定图表的配置项和数据
      const option = {
        tooltip: {
          trigger: "item",
          formatter: '{a} <br/>{b}: {c}个 ({d}%)'
        },
        title: {
          text: "POD实例状态统计",
          left: "center",
        },
        color: ["#98f6fb", "#3E76EA"],
        legend: {
          right: "10",
          orient: 'vertical',
          bottom: "10",
        },
        series: [
          {
            name: "POD",
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              // show: false,
              // position: "center",
              // formatter: `${(3 / 4) * 100 + "%"}`,
              formatter: '{b}: {c}'
              // fontSize: 30,
            },
            // emphasis: {
            //   label: {
            //     show: true,
            //     fontSize: 40,
            //     fontWeight: "bold",
            //     position: "center",
            //   },
            //   itemStyle: {
            //     shadowBlur: 10,
            //     shadowOffsetX: 0,
            //     shadowColor: 'rgba(0, 0, 0, 0.5)'
            //   }
            // },
            // labelLine: {
            //   show: false,
            // },
            data: [
              { value: `${this.resourceInfo.podRunning}`, name: "正常" },
              { value: `${this.resourceInfo.podFailed}`, name: "异常" },
            ],
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      podChart.setOption(option);
    },
    initLogType() {
      // 基于准备好的dom，初始化echarts实例
      const logChart = this.$echarts.init(this.$refs.logChart);
      // 指定图表的配置项和数据
      const option = {
        title: {
          text: '审计日志统计'
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          right: "10",
          // orient: 'vertical',
          bottom: "10",
        },
        // grid: {
        //   left: '3%',
        //   right: '4%',
        //   bottom: '3%',
        //   containLabel: true
        // },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.getLastSevenDays(),
          axisLabel: {
            show: true,
            fontSize: 12, // 根据需要调整字体大小
            interval: 0 // 设置为0以显示所有坐标点
          },
        },
        yAxis: {
          type: 'value',
          name: "单位（条）",
          // axisLabel: {
          //   formatter: '{value} 条'
          // }
        },
        series: [
          {
            name: '登录操作',
            type: 'line',
            // stack: 'Total',
            data: this.loginData,
          },
          {
            name: '应用商店',
            type: 'line',
            // stack: 'Total',
            data: this.appStoreData,
          },
          {
            name: '应用管理',
            type: 'line',
            // stack: 'Total',
            data: this.managerData,
          }
        ]
      };
      // 使用刚指定的配置项和数据显示图表。
      logChart.setOption(option);
    },
    getHomePageResources() {
      this.$appManageApi.getHomePageResources().then(res => {
        if (res && res.code === 200) {
          this.resourceInfo = res.data;
          this.initCpuType();
          this.initMemType();
          this.initPodType();
        }
      })
    },
    getHomePageTop() {
      this.$appManageApi.getHomePageTop().then(res => {
        this.serviceData = res.data;
      })
    },
    getHomePageLog() {
      this.$appManageApi.getHomePageLog().then(res => {
        let loginFilter = res.data.filter(ele => ele.category === "Login");
        if (loginFilter.length > 0) {
          this.loginData = this.getLogNumber(loginFilter[0].data);
        } else {
          this.loginData = [0, 0, 0, 0, 0, 0, 0];
        }
        let appStoreFilter = res.data.filter(ele => ele.category === "Appstore");
        if (appStoreFilter.length > 0) {
          this.appStoreData = this.getLogNumber(appStoreFilter[0].data);
        } else {
          this.appStoreData = [0, 0, 0, 0, 0, 0, 0];
        }
        let managerFilter = res.data.filter(ele => ele.category === "Manager");
        if (managerFilter.length > 0) {
          this.managerData = this.getLogNumber(managerFilter[0].data);
        } else {
          this.managerData = [0, 0, 0, 0, 0, 0, 0];
        }
        this.initLogType();
      })
    },
    getLogNumber(logList) {
      let tmpNumberList = []
      this.getLastSevenDays().forEach((item) => {
        let filter = logList.filter(e => e.day === item);
        if (filter.length > 0) {
          tmpNumberList.push(filter[0].count);
        } else {
          tmpNumberList.push(0);
        }
      });
      return tmpNumberList;
    },
    getLastSevenDays() {
      let dates = [];
      let now = new Date();
      for (let i = 6; i >= 0; i--) {
        let format = dayjs(now.getTime() - i * 24 * 60 * 60 * 1000).format('YYYY-MM-DD');
        dates.push(format);
      }
      return dates;
    },
    getHomePageData() {
      this.$appStoreApi.getHomePageData().then(res => {
        if (res && res.code === 200) {
          this.appStoreInfo = res.data;
        }
      })
    },
    onMouseOver(event) {
      const ev = event.target;
      const evWeight = ev.scrollWidth;
      const contentWidth = ev.clientWidth;
      if (evWeight > contentWidth) {
        this.isShowTooltip = false;
      } else {
        this.isShowTooltip = true;
      }
    },
  },
  mounted() {
    setTimeout(() => {
      this.getHomePageData();
      this.getHomePageTop();
      this.getHomePageLog();
      this.getHomePageResources();
    }, 500);
    window.addEventListener('resize', () => this.chartResize())
  },
  beforeDestroy() {
    // 组件销毁前 移除监听事件。 重要代码
    window.removeEventListener('resize', () => this.chartResize())
  },
};
</script>

<style scoped>
.resource-stats {
  background-color: #fff;
  margin-top: 15px;
}

.headContainer {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
}

.pie-chart {
  width: 100%;
  height: 100%;
}
</style>
